package com.ty.blog.service.blog;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ty.blog.common.exception.SKYException;
import com.ty.blog.common.utils.Page;
import com.ty.blog.entity.BaseEntity;
import org.apache.commons.lang3.ObjectUtils;

import java.lang.reflect.Field;

import static com.ty.blog.common.text.StrFormatter.propertyToField;

/**
 * @author zhutianyu
 * @date 2021/7/28 18:47
 */
public interface BaseService<E extends BaseEntity, P extends Page> {

  /** 构建查询对象 */
  default Wrapper<E> buildQueryWrapper(P p) {
    QueryWrapper<E> queryWrapper = new QueryWrapper<>();
    for (Field f : p.getClass().getDeclaredFields()) {
      f.setAccessible(true);
      Object value = null;
      try {
        value = f.get(p);
      } catch (IllegalAccessException illegalAccessException) {
        throw new SKYException("构建查询对象异常:" + JSON.toJSONString(p));
      }
      if (ObjectUtils.isNotEmpty(value)) {
        queryWrapper.eq(propertyToField(f.getName()), value);
      }
    }
    return queryWrapper;
  }
  ;
}
